package net.sunzc.yunlian.interact.device.mini;

import net.sunzc.yunlian.controller.entity.Point;
import net.sunzc.yunlian.interact.device.CommandInteract;
import net.sunzc.yunlian.utils.Utils;
import org.apache.mina.core.buffer.IoBuffer;

import java.io.File;

/**
 * Created by Administrator on 2016/9/18.
 */
public class Mouse2Touch implements Gesture, MiniManager.MiniListener {
    private static final char TOUCH = 'm';
    private static final char DOWN = 'd';
    private static final char UP = 'u';
    private final MiniManager miniManager;

    public Mouse2Touch(CommandInteract device) {
        miniManager = new MiniManager(device);
        miniManager.configureSession().setWriterIdleTime(30 * 60 * 1000);//30分钟后没有写操作则空闲
        File miniTouchBinFile = new File(System.getProperty("user.dir"), "yunlian\\" + device.getAbi() + "\\yunlian");
        miniManager.install(miniTouchBinFile, true);
        miniManager.portForward(Utils.getFreePort(), "minitouch");
        miniManager.setOnReceiveListener(this);
        miniManager.start();
    }

    private void action(char action, Point point) {
        String command = String.format(action + " 0 %s %s 50\n", point.getX(), point.getY());
        executeTouch(command);
    }

    @Override
    public void onTouch(Point point) {
        action(TOUCH, point);
    }

    @Override
    public void onDown(Point point) {
        action(DOWN, point);
    }

    private void executeTouch(String command) {
        miniManager.send(command);
        miniManager.send("c\n");
    }

    @Override
    public void onRelease() {
        String command = UP + " 0\n";
        executeTouch(command);
    }

    @Override
    public void stopGesture() {
        miniManager.stop();
    }

    @Override
    public void restartGesture() {
        miniManager.restart();
    }

    @Override
    public void onReceive(Object message) {
        new MotorHeader(((IoBuffer) message).array());
    }
}
